package com.reader.cms.controller.sys;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.reader.cms.entity.sys.SysRole;
import com.reader.cms.mapper.sys.SysRoleMapper;
import com.reader.cms.service.sys.ISysRoleService;
import org.springframework.web.bind.annotation.*;
import com.reader.cms.controller.BaseController;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import com.reader.core.entity.ResultMessageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.List;
import java.util.Map;

import com.reader.core.exception.CustomException;
import com.reader.core.validator.group.AddGroup;
import com.reader.core.utils.ValidatorUtil;
import com.baomidou.mybatisplus.plugins.Page;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author gumenghao
 * @description 功能描述
 * @date 2018-09-25
 */
@RestController
@RequestMapping("/api/sysrole")
public class SysRoleController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(SysRoleController.class);

    @Autowired
    public ISysRoleService iSysRoleService;

    @Autowired
    SysRoleMapper sysRoleMapper;

    /**
     * @param currentPage 当前页
     * @param size        每页记录数
     * @param name        其它查询条件，根据情况动态添加
     * @return ResultMessageInfo
     * @function 分页查询数据
     */
    @GetMapping("list")
    public ResultMessageInfo selectListPage(@RequestParam(value = "currentPage") int currentPage,
                                            @RequestParam(value = "size") int size,
                                            @RequestParam(value = "name") String name) {
        ResultMessageInfo resultMessage = null;
        Page<Map<String, Object>> list = iSysRoleService.selectListPage(currentPage, size, name);
        return ResultMessageInfo.ofSuccess("查询成功！", list);
    }

    /**
     * 获取所有可用角色
     *
     * @return
     */
    @GetMapping("all")
    public ResultMessageInfo getAllRoles() {
        ResultMessageInfo resultMessage = null;
        List<SysRole> list = iSysRoleService.selectAllRoles();
        return ResultMessageInfo.ofSuccess("查询成功！", list);
    }


    /**
     * 获取组织机构对应的角色
     *
     * @param code
     * @return
     */
    @GetMapping("roleOfOrganization")
    public ResultMessageInfo getRolesOfUser(@RequestParam(value = "code") String code) {
        ResultMessageInfo resultMessage = null;
        List<SysRole> list = iSysRoleService.getRolesOfOrganization(code);
        return ResultMessageInfo.ofSuccess("查询成功！", list);
    }

    /**
     * 获取用户所拥有的角色
     *
     * @param id
     * @return
     */
    @GetMapping("roleOfUser")
    public ResultMessageInfo getRolesOfUser(@RequestParam(value = "id") Integer id) {
        ResultMessageInfo resultMessage = null;
        List<Integer> list = iSysRoleService.getRolesOfUserId(id);
        return ResultMessageInfo.ofSuccess("查询成功！", list);
    }

    /**
     * 给角色赋予对应权限
     *
     * @param sysRole
     * @return
     */
    @PostMapping("configPer")
    public ResultMessageInfo configPermission(@RequestBody SysRole sysRole) {
        ResultMessageInfo resultMessage = null;
        iSysRoleService.configPermission(sysRole);
        return ResultMessageInfo.ofSuccess("角色权限配置成功！");
    }

    /**
     * @param sysRole 实体对象
     * @return
     * @function 添加新记录
     */
    @PostMapping("insert")
    public ResultMessageInfo insert(@RequestBody SysRole sysRole) {
        ValidatorUtil.validateEntity(sysRole, AddGroup.class);//非空验证
        EntityWrapper<SysRole> wrapper = new EntityWrapper<>();
        wrapper.eq("del_flag", 0).eq("name", sysRole.getName());
        Integer detailCount = sysRoleMapper.selectCount(wrapper);
        if (detailCount != 0) {
            return ResultMessageInfo.ofMessage("角色名称已存在！");
        }
        ResultMessageInfo resultMessage = null;
        Integer userId = this.getUserId();
        sysRole.setInsertDt(new Date());
        sysRole.setDelFlag(0);
        sysRole.setEnable(1);
        sysRole.setInsertUserId(userId);
        sysRole.setUpdtUserId(userId);
        boolean resultValue = iSysRoleService.insert(sysRole);
        if (!resultValue) {
            return ResultMessageInfo.ofMessage("添加失败！");
        }
        return ResultMessageInfo.ofSuccess("添加成功！");
    }

    /**
     * @param sysRole 实体对象
     * @return
     * @function 修改
     */
    @PostMapping("update")
    @Transactional
    @ApiOperation(value = "跟据ID列新记录", notes = "id为必须项")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "要更新对象ID", required = true, dataType = "int", paramType = "path")})
    public ResultMessageInfo update(@RequestBody SysRole sysRole) {
        ValidatorUtil.validateEntity(sysRole, AddGroup.class);//非空验证
        EntityWrapper<SysRole> wrapper = new EntityWrapper<>();
        wrapper.eq("del_flag", 0).eq("name",
                sysRole.getName()).ne("id", sysRole.getId());
        Integer detailCount = sysRoleMapper.selectCount(wrapper);
        if (detailCount != 0) {
            return ResultMessageInfo.ofMessage("角色名称已存在！！！");
        }
        ResultMessageInfo resultMessage = null;
        Integer userId = this.getUserId();
        sysRole.setUpdtUserId(userId);
        sysRole.setUpdtDt(new Date());
        sysRole.setDelFlag(0);
        boolean resultValue = iSysRoleService.updateById(sysRole);
        if (!resultValue) {
            return ResultMessageInfo.ofMessage("修改失败！");

        }
        return ResultMessageInfo.ofSuccess("修改成功！");
    }

    /**
     * @param sysRole 实体对象
     * @return
     * @function 删除
     */
    @PostMapping("delete")
    @Transactional
    @ApiOperation(value = "跟据ID列新记录", notes = "id为必须项")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "要更新对象ID", required = true, dataType = "int", paramType = "path")})
    public ResultMessageInfo delete(@RequestBody SysRole sysRole) {
        ResultMessageInfo resultMessage = null;
        boolean flag = iSysRoleService.judgeDel(sysRole.getId());
        if (!flag) {
            return ResultMessageInfo.ofMessage("用户已使用角色，不能删除！！！");
        }
        Integer userId = this.getUserId();
        sysRole.setUpdtUserId(userId);
        sysRole.setUpdtDt(new Date());
        sysRole.setDelFlag(1);
        boolean resultValue = iSysRoleService.updateById(sysRole);
        if (!resultValue) {
            ResultMessageInfo.ofMessage("删除失败！");
        }
        return ResultMessageInfo.ofSuccess("删除成功！");
    }

    /**
     * @param data 键为ids值为整型数组的json格式
     * @return
     * @function 批量删除对象
     */
    @PostMapping("deleteIds")
    @Transactional
    @ApiOperation(value = "跟据ID删除记录", notes = "键为ids值为整型数组的json格式")
    @ApiImplicitParams({@ApiImplicitParam(name = "ids", value = "id列表", required = true, dataType = "int", paramType = "path")})
    public ResultMessageInfo deleteBatchIds(@RequestBody String data) {
        ResultMessageInfo resultMessage = null;
        List<Long> ids = JSON.parseArray(JSON.parseObject(data).getString("ids"), Long.class);
        boolean resultValue = iSysRoleService.deleteBatchIds(ids);
        if (resultValue) {
            resultMessage = ResultMessageInfo.ofSuccess("删除成功!", resultValue);
        } else {
            return ResultMessageInfo.ofMessage("删除失败!");
        }
        return resultMessage;

    }
}